const httpx = require('httpx');
const _ = require('lodash');
const Controller = require('egg').Controller;
const place_title = require('../../web/utils/place-title.js');

const {
	origin,
	username,
	password,
	appointmentTpl,
	queueupTpl,
	cancelTpl,
} = require('../../../config/server');

const isWx = ua => {
	return /micromessenger/i.test(ua);
};

const parseJSON = data => {
	return {
		dataType: 'json',
		method: 'POST',
		data: JSON.stringify(data),
		headers: {
			'Content-Type': 'application/json',
			Accept: 'application/json',
		},
	};
};

const request = async (url, opts = {}) => {
	const options = Object.assign({}, this.defaults);
	for (const key in opts) {
		if (key !== 'headers') {
			options[key] = opts[key];
		} else {
			if (opts.headers) {
				options.headers = options.headers || {};
				Object.assign(options.headers, opts.headers);
			}
		}
	}

	let data;
	try {
		const response = await httpx.request(url, options);
		const text = await httpx.read(response, 'utf8');
		data = JSON.parse(text);
	} catch (err) {
		err.name = 'APIRequest' + err.name;
		throw err;
	}
	if (data.errcode) {
		const err = new Error(data.errmsg);
		err.name = 'APIRequestError';
		err.code = data.errcode;
		throw err;
	}
	return data;
};

class AppController extends Controller {

	async handleApi(path, ctx, req, res) {
		console.log('api path =>', path, ', body =>', res);
		const ua = ctx.get('User-Agent');
		switch (path) {
		case 'SubmitYYInfo':
			if (isWx(ua) && res.resultcode == 1 && req.openid) {
				const info = res.resultmsg.split(',');
				const data = {
					[appointmentTpl.titleKey]: { value: '预约成功通知', color: '#FF0000' },
					[appointmentTpl.companyKey]: { value: place_title, color: '#FF0000' },
					[appointmentTpl.itemKey]: { value: info[6], color: '#FF0000' },
					[appointmentTpl.dateKey]: { value: info[2], color: '#FF0000' },
					[appointmentTpl.durationKey]: { value: info[3], color: '#FF0000' },
					[appointmentTpl.addressKey]: { value: info[4], color: '#FF0000' },
					[appointmentTpl.remarkKey]: { value: '您好，您已预约成功。', color: '#FF0000' },
				};
				return ctx.app.wechatApi.sendTemplate(
					req.openid,
					appointmentTpl.id,
					'',
					'',
					'index?foo=bar',
					data,
					appointmentTpl.topColor
				);
			}
			break;
		case 'SubmitTSYYInfo':
			if (isWx(ua) && res.resultcode == 1 && req.openid) {
				const info = res.resultmsg.split(',');
				const data = {
					[appointmentTpl.titleKey]: { value: '开发商预约成功通知', color: '#FF0000' },
					[appointmentTpl.companyKey]: { value: place_title, color: '#FF0000' },
					[appointmentTpl.itemKey]: { value: info[4], color: '#FF0000' },
					[appointmentTpl.dateKey]: { value: info[0], color: '#FF0000' },
					[appointmentTpl.durationKey]: { value: info[1], color: '#FF0000' },
					[appointmentTpl.addressKey]: { value: info[2], color: '#FF0000' },
					[appointmentTpl.remarkKey]: { value: `单位组织机构代码：${info[5]}`, color: '#FF0000' },
				};
				return ctx.app.wechatApi.sendTemplate(
					req.openid,
					appointmentTpl.id,
					'',
					'',
					'index?foo=bar',
					data,
					appointmentTpl.topColor
				);
			}
			break;
		case 'SubmitQHInfo':
			if (isWx(ua) && res.resultcode == 1 && req.wxh) {
				const info = res.noInfo[0];
				const listData = await request(
					`${origin}/WSYY/GetAllNo`,
					parseJSON({ strJson: JSON.stringify({ username, password }) })
				);

				if (listData.resultcode && listData.resultcode == 1 && listData.noInfo) {
					const index = _.findIndex(listData.noInfo, item => info.deal_no === item.deal_no);
					const len = index === -1 ? 0 : index;
					const data = {
						[queueupTpl.titleKey]: { value: '恭喜您取号成功', color: '#FF0000' },
						[queueupTpl.queueNoKey]: { value: info.deal_no, color: '#FF0000' },
						[queueupTpl.itemKey]: { value: info.ywlx, color: '#FF0000' },
						[queueupTpl.queueCountKey]: { value: len, color: '#FF0000' },
						[queueupTpl.timeKey]: { value: info.getno_date, color: '#FF0000' },
						[queueupTpl.remarkKey]: { value: '感谢您的使用。', color: '#FF0000' },
					};
					return ctx.app.wechatApi.sendTemplate(
						req.wxh,
						queueupTpl.id,
						'',
						'',
						'index?foo=bar',
						data,
						queueupTpl.topColor
					);
				}
			}
			break;
		case 'CancelYYInfoByID':
			const openid = ctx.cookies.get('openid');
			if (isWx(ua) && res.resultcode == 1 && openid) {
				const params = {
					yyid: req.id,
					yyr: req.yyr,
					zjhm: req.zjhm,
					qzhm: req.qzhm,
					yyh: req.yyh,
				};
				const result = await request(
					`${origin}/WSYY/SearchYYInfo`,
					parseJSON({ strJson: JSON.stringify({ ...params, username, password }) })
				);

				if (result.resultcode && result.resultcode == 1 && result.yyinfo && result.yyinfo.length > 0) {
					const info = result.yyinfo[0];
					const data = {
						[cancelTpl.titleKey]: { value: '预约取消成功通知', color: '#FF0000' },
						[cancelTpl.companyKey]: { value: place_title, color: '#FF0000' },
						[cancelTpl.itemKey]: { value: info.yysx, color: '#FF0000' },
						[cancelTpl.dateKey]: { value: info.yyrq, color: '#FF0000' },
						[cancelTpl.durationKey]: { value: info.yysd, color: '#FF0000' },
						[cancelTpl.addressKey]: { value: info.wddz, color: '#FF0000' },
						[cancelTpl.remarkKey]: { value: '您好，您已成功取消预约。', color: '#FF0000' },
					};
					return ctx.app.wechatApi.sendTemplate(
						openid,
						cancelTpl.id,
						'',
						'',
						'index?foo=bar',
						data,
						cancelTpl.topColor
					);
				}
			}
			break;
		default:
			break;
		}
	}

	async index() {
		const { ctx } = this;
		const { query } = ctx;
		const ua = ctx.get('User-Agent');
		const data = { url: ctx.url };
		if (isWx(ua) && query.code) {
			const info = await ctx.app.wechatOauth.getAccessToken(query.code);
			ctx.cookies.set('openid', info.data.openid, {
				maxAge: 1000 * 60 * 60 * 24 * 30,
				httpOnly: false,
			});
		}
		await ctx.render('app/app.js', data);
	}

	async api() {
		const { ctx } = this;
		const oldBody = ctx.request.body;
		const oldStrJson = oldBody && oldBody.strJson ? JSON.parse(oldBody.strJson) : {};
		const newStrJson = Object.assign({}, { username, password }, oldStrJson);
		const apiPath = ctx.url.split('?')[0].replace('/api/WSYY/', '');

		ctx.logger.info('API PATH =>', ctx.url);
		ctx.logger.info('API REQUEST BODY =>', oldBody);

		const res = await request(`${origin}/WSYY/${apiPath}`, parseJSON({ strJson: JSON.stringify(newStrJson) }));

		ctx.logger.info('API RESPONSE =>', res);

		ctx.body = res;
		ctx.status = 200;

		try {
			await this.handleApi(apiPath, ctx, oldStrJson, res);
		} catch (err) {
			ctx.logger.error(err);
			console.log(`${err.name} => ${err.code}`);
		}
	}
}

module.exports = AppController;
